//
//  ZDNetworkTool.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/10/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDNetworkTool.h"
#import <AFNetworking/AFNetworking.h>
#import "ZDUserAccount.h"

@interface ZDNetworkTool ()


@property (nonatomic, strong) AFHTTPSessionManager *afnManager;


@property (nonatomic, copy, readonly) NSString *baseURL;

/**
 *  申请应用时分配的AppKey
 */
@property (nonatomic, copy, readonly) NSString *client_id;

/**
 *  授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址
 */
@property (nonatomic, copy, readonly) NSString *redirect_uri;

/**
 *  申请应用时分配的AppSecret
 */
@property (nonatomic, copy, readonly) NSString *client_secret;


@end

@implementation ZDNetworkTool

#pragma mark - 创建单例
+ (instancetype)sharedInstance
{
    static ZDNetworkTool *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
    });
    
    return instance;
}

#pragma mark - 只读私有属性
- (NSString *)baseURL
{
    return @"https://api.weibo.com/";
}

- (NSString *)client_id
{
    return @"1671583110";
}

- (NSString *)redirect_uri
{
    return @"http://www.baidu.com/";
}

- (NSString *)client_secret
{
    return @"c028d8532a2f7d72cb17a5462474e589";
}


#pragma mark - 方法
/**
 *  返回授权URL
 */
- (NSURL *)authURL
{
    NSString *urlString = [NSString stringWithFormat:@"%@oauth2/authorize?client_id=%@&redirect_uri=%@", self.baseURL, self.client_id, self.redirect_uri];
    
//    ZDLog(@"%@", urlString);
    
    return [NSURL URLWithString:urlString];
}


/**
 *  加载accessToken
 *
 *  @param code         授权成功 返回的code
 *  @param successBlock 请求成功回调
 *  @param failureBlock 请求失败回调
 */
- (void)loadAccessToken:(NSString *)code success:(void (^)(id responseObject))successBlock failure:(void (^)(NSError *error))failureBlock
{
    //断言
    NSAssert(successBlock != nil, @"成功回调block不能为空");
    NSAssert(failureBlock != nil, @"失败回调block不能为空");
    
    //拼接urlString
    NSString *urlString = [NSString stringWithFormat:@"%@oauth2/access_token", self.baseURL];
    
    //配置请求参数
#warning 注意：请求参数一定要严格按照要求配置 多一个空格都不行 否则报错400 服务器不能识别请求
    NSDictionary *parameters = @{
                                 @"client_id" : self.client_id,
                                 @"client_secret" : self.client_secret,
                                 @"grant_type" : @"authorization_code",
                                 @"code" : code,
                                 @"redirect_uri" : self.redirect_uri
                                };
    
    //添加可解析类型
    self.afnManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    
    [self.afnManager POST:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
//        ZDLog(@"responseObject: %@", responseObject);
        
        successBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
//        ZDLog(@"error: %@", error);
        
        failureBlock(error);
    }];
}


/**
 *  加载用户信息
 *
 *  @param access_token access_Token
 *  @param uid          uid
 *  @param successBlock 请求成功回调
 *  @param failureBlock 请求失败回调
 */
- (void)loadUserInfoWithAccess_token:(NSString *)access_token uid:(NSString *)uid success:(void (^)(id responseObject))successBlock failure:(void (^)(NSError *error))failureBlock
{
    //断言
    NSAssert(successBlock != nil, @"成功回调block不能为空");
    NSAssert(failureBlock != nil, @"失败回调block不能为空");
    
    //拼接urlString    https://api.weibo.com/2/users/show.json
    NSString *urlString = [NSString stringWithFormat:@"%@2/users/show.json", self.baseURL];
    
    //配置请求参数
    NSDictionary *parameters = @{
                                 @"access_token" : access_token,
                                 @"uid" : uid
                                };

    [self GET:urlString parameters:parameters success:^(id responseObject) {
        
        successBlock(responseObject);
        
    } failure:^(NSError *error) {
        
        failureBlock(error);
    }];
    
//    [self.afnManager GET:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        
//        successBlock(responseObject);
//        
//    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//        
//        failureBlock(error);
//    }];
}


/**
 *  加载微博数据
 *
 *  @param access_token access_Token
 *  @param since_id     若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
 *  @param max_id       若指定此参数，则返回ID小于或等于max_id的微博，默认为0
 *  @param successBlock 请求成功回调
 *  @param failureBlock 请求失败回调
 */
- (void)loadStatusesWithAccess_token:(NSString *)access_token since_id:(int64_t)since_id max_id:(int64_t)max_id success:(void (^)(id responseObject))successBlock failure:(void (^)(NSError *error))failureBlock
{
    /* https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00bNZZqBuHnHpBe08d4a2797lO576C */
    
    //断言
    NSAssert(successBlock != nil, @"成功回调block不能为空");
    NSAssert(failureBlock != nil, @"失败回调block不能为空");
    
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@2/statuses/home_timeline.json", self.baseURL];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:access_token forKey:@"access_token"];
    
    if (since_id > 0)
    {
        [parameters setObject:@(since_id) forKey:@"since_id"];
    }
    
    if (max_id > 0)
    {
        [parameters setObject:@(max_id-1) forKey:@"max_id"];
    }
    
    
    [self GET:urlString parameters:parameters success:^(id responseObject) {
        
        successBlock(responseObject);
        
    } failure:^(NSError *error) {
        
        failureBlock(error);
        
    }];
}


#pragma mark - 进一步封装AFN GET 使用一个自己的方法来管理AFN GET请求
- (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))successBlock failure:(void (^)(NSError *error))failureBlock
{
    [self.afnManager GET:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        successBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        failureBlock(error);
    }];
}



/**
 *  发微博
 *
 *  @param status       微博内容
 *  @param image        微博配图  新浪默认最多可上传9张，但是开发账号只能上传一张，所以这里只要求传入一张
 *  @param access_token access_token
 *  @param successBlock 成功回调
 *  @param failureBlock 失败回调
 */
- (void)sendStatus:(NSString *)status image:(UIImage *)image access_token:( NSString *)access_token success:(void (^)(id   responseObject))successBlock failure:(void (^)(NSError * error))failureBlock
{
    //断言
    NSAssert(successBlock != nil, @"成功回调block不能为空");
    NSAssert(failureBlock != nil, @"失败回调block不能为空");
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setObject:access_token forKey:@"access_token"];
    [parameters setObject:status forKey:@"status"];
    
    if (image)
    {
        //https://upload.api.weibo.com/2/statuses/upload.json
        
        NSString *urlString = @"https://upload.api.weibo.com/2/statuses/upload.json";
        
        //发表带图片的微博
        [self.afnManager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *data = UIImagePNGRepresentation(image);
            
            [formData appendPartWithFileData:data name:@"pic" fileName:@"" mimeType:@"image/png"];
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            successBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
            failureBlock(error);
        }];
    }
    else
    {
        //https://api.weibo.com/2/statuses/update.json
        
        NSString *urlString = [NSString stringWithFormat:@"%@2/statuses/update.json", self.baseURL];
        
        //发表纯文本微博
        [self.afnManager POST:urlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            successBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
            failureBlock(error);
        }];
    }
}


#pragma mark 懒加载
- (AFHTTPSessionManager *)afnManager
{
    if (!_afnManager)
    {
        _afnManager = [[AFHTTPSessionManager alloc] init];
    }
    
    return _afnManager;
}

@end
